package com.lz.ionicbase.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.lz.ionicbase.R;
import com.lz.ionicbase.SuperApp;
import com.lz.ionicbase.utils.Constant;
import com.lz.ionicbase.utils.DpUtil;
import com.lz.ionicbase.utils.SpUtils;
import com.lz.ionicbase.widget.Notice;
import com.lz.ionicbase.widget.WheelDatePickerDialog;


public class BaseWebViewActivity extends BaseActivity {

    private static final String TAG = "BaseWebViewActivity";
    private static final String KEY_URL = "url";
    private static final String KEY_DATA = "data";
    private static final String KEY_ENCODING = "encoding";
    private WebView mWebView;
    //    protected Stack<String> stack = new Stack<String>();
    private String textEncoding;
    private SwipeRefreshLayout swipeLayout;

    private Activity context;
    private RelativeLayout errorpage;

    private MyWebClient myWebClient = new MyWebClient();
    private MyWebChromeClient myWebChromeClient = new MyWebChromeClient();

    private Handler netHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
                errorpage.setVisibility(View.VISIBLE);
                mWebView.setVisibility(View.GONE);
            }else if(msg.what==0){
                errorpage.setVisibility(View.GONE);
                mWebView.setVisibility(View.VISIBLE);
            }
        }
    };
    private RelativeLayout content_rl;

    @Override
    protected void initView() {
        context = this;
        Intent intent = this.getIntent();

        String url = intent.getStringExtra(KEY_URL);
        String data = intent.getStringExtra(KEY_DATA);
        textEncoding = intent.getStringExtra(KEY_ENCODING);

        mWebView = (WebView) findViewById(R.id.webview);
        setWebView();

        if (url != null && !"".equals(url)) {
            mWebView.loadUrl(url);
        } else if (data != null && !"".equals(data)) {
            mWebView.loadDataWithBaseURL(null, data, null, "utf-8", null);
        }

        errorpage = (RelativeLayout) findViewById(R.id.errorpage);
        swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        swipeLayout.setColorSchemeResources(R.color.app_base);
        swipeLayout.setProgressViewOffset(true, DpUtil.dip2px(this, 100), DpUtil.dip2px(this, 150));
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mWebView.reload();
            }
        });
        swipeLayout.setEnabled(false);

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.reload();
            }
        });
        findViewById(R.id.back_ib).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        content_rl = (RelativeLayout) findViewById(R.id.content_rl);
    }

    private void setWebView() {

        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);// 滚动条风格，为0就是不给滚动条留空间，滚动条覆盖在网页上

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setDefaultTextEncodingName(textEncoding == null ? "UTF-8" : textEncoding);//设置编码
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);//设置显示缩放按钮
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        //自适应屏幕
        webSettings.setUseWideViewPort(true);//将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小

        webSettings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        webSettings.setSupportMultipleWindows(true);// 设置允许开启多窗口

        webSettings.setDomStorageEnabled(true);// 开启 DOM storage API 功能
//        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//优先从本地cache中载入，其次才是从网络中载入，即使cache已经过期。
//        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存
        webSettings.setAppCacheEnabled(true);       //开启 Application Caches 功能
        String cacheDirPath = getCacheDir().getAbsolutePath()+ "WebView";
        webSettings.setDatabasePath(cacheDirPath);  //设置数据库缓存路径
        webSettings.setAppCachePath(cacheDirPath);  //设置  Application Caches 缓存目录

        webSettings.setAllowFileAccess(true);  //设置可以访问文件
        //webSettings.setDefaultFontSize(16);//设置默认字体大小
        mWebView.requestFocusFromTouch();//手势焦点

        mWebView.setWebViewClient(myWebClient);
        mWebView.setWebChromeClient(myWebChromeClient);

        mWebView.addJavascriptInterface(new JScriptObject(this), "androidObj");

//        mWebView.clearCache(true);//用于测试----清除 内存+磁盘 缓存
    }


    @Override
    protected int getActivityLayout() {
        return R.layout.layout_webview;
    }

    private class MyWebClient extends WebViewClient {

        boolean isError = false;
        boolean errorBefore = false;
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;//返回false,新链接地址使用WebView 加载该 url。否则使用系统浏览器等
        }

        @Override
        //在页面加载开始时调用
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
//            swipeLayout.setRefreshing(true);
        }

        @Override
        //页面结束时调用----此API可能有BUG,调用此方法的时间不准确
        public void onPageFinished(WebView view, String url) {
            swipeLayout.setRefreshing(false);

            Log.e(TAG, "url=="+url);
            if(isError){
                //错误
                Log.e(TAG, "错误回调!!!!");
                errorBefore = true;
                isError = false;
                netHandler.sendEmptyMessage(1);
            }else if(errorBefore){
                errorBefore = false;
                Log.e(TAG, "系统错误页面加载完成!!!!");
            }else {
                netHandler.sendEmptyMessage(0);
                Log.e(TAG, "正常页面完成!!!!");
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
//            view.loadUrl("file:///android_asset/ceshi.html");
            Log.e(TAG, "错误码:"+errorCode);
            Log.e(TAG, description);
            isError = true;
        }
    }

    private void initWebView(WebView webView) {
        WebSettings webSettings = webView.getSettings();

        webSettings.setSupportMultipleWindows(true);// 设置允许开启多窗口
        webSettings.setDomStorageEnabled(true);//
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据

        webSettings.setJavaScriptEnabled(true);// 设置支持javascript
        webView.addJavascriptInterface(new JScriptObject(this), "androidObj");
    }

    private class MyWebChromeClient extends WebChromeClient {

        WebView newWebView;
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // setProgress(newProgress * 1000);
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog,
                                      boolean isUserGesture, Message resultMsg) {//html中调用window.open()，会回调此函数
            Log.e("onCreateWindow","创建新窗口：" + isDialog + ";" + isUserGesture + ";" + resultMsg);
            newWebView = new WebView(context);  //新创建一个webview
            content_rl.addView(newWebView);     //把webview加载到activity界面上

            newWebView.setWebViewClient(new MyWebClient());
            newWebView.setWebChromeClient(this);

            initWebView(newWebView);//初始化webview

            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;//以下的操作应该就是让新的webview去加载对应的url等操作。
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();
            return true;
        }

        @Override
        public void onCloseWindow(WebView window) {//html中，用js调用.close(),会回调此函数
            super.onCloseWindow(window);
            Log.e("onCloseWindow","关闭当前窗口");
            if (newWebView != null) {
                content_rl.removeView(newWebView);
            }
        }

        /**
         * 覆盖默认的window.alert展示界面，避免title里显示为“：来自file:////”
         */
        public boolean onJsAlert(WebView view, String url, String message,
                                 JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(
                    view.getContext());

            builder.setTitle("对话框").setMessage(message)
                    .setPositiveButton("确定", null);

            // 不需要绑定按键事件
            // 屏蔽keycode等于84之类的按键
            builder.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(DialogInterface dialog, int keyCode,
                                     KeyEvent event) {
                    Log.v("onJsAlert", "keyCode==" + keyCode + "event=" + event);
                    return true;
                }
            });
            // 禁止响应按back键的事件
            builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
            return true;
            // return super.onJsAlert(view, url, message, result);
        }


        /**
         * 覆盖默认的window.confirm展示界面，避免title里显示为“：来自file:////”
         */
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(
                    view.getContext());
            builder.setTitle("对话框").setMessage(message)
                    .setPositiveButton("确定", new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    }).setNeutralButton("取消", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });
            builder.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    result.cancel();
                }
            });

            // 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
            builder.setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode,
                                     KeyEvent event) {
                    Log.v("onJsConfirm", "keyCode==" + keyCode + "event="
                            + event);
                    return true;
                }
            });
            // 禁止响应按back键的事件
            // builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            return true;
        }

        /**
         * 覆盖默认的window.prompt展示界面，避免title里显示为“：来自file:////”
         * window.prompt('请输入您的域名地址', '618119.com');
         */
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, final JsPromptResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(
                    view.getContext());

            builder.setTitle("对话框").setMessage(message);

            final EditText et = new EditText(view.getContext());
            et.setSingleLine();
            et.setText(defaultValue);
            builder.setView(et).setPositiveButton("确定", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm(et.getText().toString());
                }

            }).setNeutralButton("取消", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });

            // 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
            builder.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(DialogInterface dialog, int keyCode,
                                     KeyEvent event) {
                    Log.v("onJsPrompt", "keyCode==" + keyCode + "event="
                            + event);
                    return true;
                }
            });

            // 禁止响应按back键的事件
            // builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            return true;
        }
    }



    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
    }

    @Override
    protected void initListener() {

    }

    private class JScriptObject {
        Activity mContxt;

        public JScriptObject(Activity mContxt) {
            this.mContxt = mContxt;
        }

        @JavascriptInterface
        public void onBack() {
//            Toast.makeText(mContxt, "JavaScriptObject本地代码调用", Toast.LENGTH_LONG).show();
            mContxt.finish();
            mContxt = null;
        }

        @JavascriptInterface
        public void onRelogon() {
            SuperApp.removeAppCookie();
            SpUtils.saveBoolean(context, Constant.ISAUTO, false);
//            Toast.makeText(mContxt, "登陆超时或在其在他手机登陆! ", Toast.LENGTH_LONG).show();
            Log.e("JScriptObject", "session超时");

            Notice.alert(context, "登陆超时或在其在他手机登陆!", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Intent intent = new Intent(context, WelcomeActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
        }

        @JavascriptInterface
        public void onCalendar() {
            WheelDatePickerDialog dailog = new WheelDatePickerDialog();
            dailog.showDatePickerDialog(BaseWebViewActivity.this, new WheelDatePickerDialog.OnWheelDateDismiss() {
                @Override
                public void onWheelDateDismiss(String age, String xingZuo, String date) {

                    final String call = "javascript:toHtmlDateTime(\"" + date + "\")";
                    mWebView.post(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.loadUrl(call);
                        }
                    });

                }
            });
        }
    }

}
